package controllers

import (
	"encoding/json"
	"errors"
	"gitee.com/lzqysoft/ilive/models"
	//	"strconv"
	"strings"

	"github.com/astaxie/beego"
	//	"gitee.com/lzqysoft/ilive/libs"
	"time"

	"strconv"
)

// oprations for Region
type RegionController struct {
	CommonController
}

func (c *RegionController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
	c.Mapping("GetRegionList", c.GetRegionList)
	c.Mapping("DeleteRegions", c.DeleteRegions)
}

// @Title Post
// @Description create Region
// @Param	body		body 	models.Region	true		"body for Region content"
// @Success 201 {int} models.Region
// @Failure 403 body is empty
// @router / [post]
func (c *RegionController) Post() {
	var v models.Region
	v.Name = c.GetString("Name")

	pid, _ := c.GetInt64("Pid")
	v.Pid = pid
	v.Attr = c.GetString("Attr")
	v.Code = c.GetString("Code")
	if pid != 0 {
		v.Level = 1
	} else {
		v.Level = 0
	}
	userInfo := c.GetSession("userinfo")
	v.Creater = userInfo.(models.User).Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime

	if id, err := models.AddRegion(&v); err == nil {
		c.Data["json"] = "ok"
		var log models.Log
		log.UserId = c.GetSession("userinfo").(models.User).Id
		log.Lon = 0
		log.Lat = 0
		log.Address = "-"
		log.Type = 1
		log.Contect = c.GetSession("userinfo").(models.User).Name + "：新建了地域，id为：" + string(id)
		log.Ip = "-"
		log.Status = 1
		log.Creater = c.GetSession("userinfo").(models.User).Name
		log.Ctime = time.Now()
		log.Updater = log.Creater
		log.Utime = log.Ctime
		models.AddLog(&log)
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// @Title Get
// @Description get Region by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Region
// @Failure 403 :id is empty
// @router /:id [get]
func (c *RegionController) GetOne() {
	id, _ := c.GetInt64(":id")
	v, err := models.GetRegionById(id)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// @Title Get All
// @Description get Region
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Region
// @Failure 403
// @router / [get]
func (c *RegionController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query map[string]string = make(map[string]string)
	var limit int64 = -1
	var offset int64 = 0

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllRegion(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = l
	}
	c.ServeJSON()
}

// @Title Update
// @Description update the Region
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Region	true		"body for Region content"
// @Success 200 {object} models.Region
// @Failure 403 :id is not int
// @router /:id [put]
func (c *RegionController) Put() {
	id, _ := c.GetInt64(":id")
	v := models.Region{Id: id}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if err := models.UpdateRegionById(&v); err == nil {
			c.Data["json"] = "OK"
			var log models.Log
			log.UserId = c.GetSession("userinfo").(models.User).Id
			log.Lon = 0
			log.Lat = 0
			log.Address = "-"
			log.Type = 1
			log.Contect = c.GetSession("userinfo").(models.User).Name + ":修改了地域信息，id为：" + string(id)
			log.Ip = "-"
			log.Status = 1
			log.Creater = c.GetSession("userinfo").(models.User).Name
			log.Ctime = time.Now()
			log.Updater = log.Creater
			log.Utime = log.Ctime
			models.AddLog(&log)
		} else {
			c.Data["json"] = err.Error()
		}
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// @Title Delete
// @Description delete the Region
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /:id [delete]
func (c *RegionController) Delete() {
	id, _ := c.GetInt64(":id")
	if err := models.DeleteRegion(id); err == nil {
		c.Data["json"] = "OK"
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// @Title GetRegionList
// @Description GetRegionList
// @Success 200 success!
// @Failure 403
// @router /GetRegionList [get]
func (c *RegionController) GetRegionList() {
	beego.Debug("router is right!")
	c.TplName = "layout/region_list.html"
}

// @Title DeleteRegions
// @Description DeleteRegions
// @Success 200 success!
// @Failure 403
// @router /DeleteRegions [post]
func (c *RegionController) DeleteRegions() {
	var idlist = c.GetStrings("idlist[]")
	for _, value := range idlist {
		id, _ := strconv.ParseInt(value, 10, 64)
		err := models.DeleteRegion(id)
		if err != nil {
			c.Data["josn"] = err.Error()
			break
		} else {
			c.Data["json"] = "ok"
			var log models.Log
			log.UserId = c.GetSession("userinfo").(models.User).Id
			log.Lon = 0
			log.Lat = 0
			log.Address = "-"
			log.Type = 1
			log.Contect = c.GetSession("userinfo").(models.User).Name + ":移除了地域，id为：" + string(id)
			log.Ip = "-"
			log.Status = 1
			log.Creater = c.GetSession("userinfo").(models.User).Name
			log.Ctime = time.Now()
			log.Updater = log.Creater
			log.Utime = log.Ctime
			models.AddLog(&log)
		}
	}

	c.ServeJSON()
}
